import { useMutation, useQueryClient } from '@tanstack/react-query';
import { message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';
import localINFO from '@/utils/localInfo';

import { Logger } from '../useLogger';

interface DeleteUserModalProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  total: number;
  page: number;
  pageSize: number;
  setPage: (page: number) => void;
  userId?: number;
}

const DeleteUserModal: React.FC<DeleteUserModalProps> = ({
  visible,
  setVisible,
  userId,
  total,
  page,
  pageSize,
  setPage,
}) => {
  const queryClient = useQueryClient();

  const DeleteUser = useMutation({
    mutationFn: (params: any) => api.DeleteUser(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('删除成功');
        if (total && page > total / pageSize && total % pageSize === 1 && page > 1) {
          setPage(page - 1);
        }
      } else {
        message.error(`删除失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('删除失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getUsersData'] }),
    mutationKey: ['getUsersData'],
  });

  const handleDeleteOk = async () => {
    if (userId) {
      DeleteUser.mutate({
        id: userId,
      });
    }
    setVisible(false);
  };

  const handleDeleteCancel = () => {
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="删除用户"
        open={visible}
        onOk={handleDeleteOk}
        onCancel={handleDeleteCancel}
        cancelText="取消"
        okText="确定"
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <p style={{ marginLeft: 24, color: 'red' }}>删除前请插入该用户的usbKey！</p>
        <p style={{ marginLeft: 24 }}>您确定要删除该用户吗？</p>
      </Modal>
    </>
  );
};

export default DeleteUserModal;
